home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / RDB.PY < prev    next >
Encoding:
Python Source  |  2000-07-17  |  10.0 KB  |  285 lines

  1. ##############################################################################
  2. # Zope Public License (ZPL) Version 1.0
  3. # -------------------------------------
  4. # Copyright (c) Digital Creations.  All rights reserved.
  5. # This license has been certified as Open Source(tm).
  6. # Redistribution and use in source and binary forms, with or without
  7. # modification, are permitted provided that the following conditions are
  8. # met:
  9. # 1. Redistributions in source code must retain the above copyright
  10. #    notice, this list of conditions, and the following disclaimer.
  11. # 2. Redistributions in binary form must reproduce the above copyright
  12. #    notice, this list of conditions, and the following disclaimer in
  13. #    the documentation and/or other materials provided with the
  14. #    distribution.
  15. # 3. Digital Creations requests that attribution be given to Zope
  16. #    in any manner possible. Zope includes a "Powered by Zope"
  17. #    button that is installed by default. While it is not a license
  18. #    violation to remove this button, it is requested that the
  19. #    attribution remain. A significant investment has been put
  20. #    into Zope, and this effort will continue if the Zope community
  21. #    continues to grow. This is one way to assure that growth.
  22. # 4. All advertising materials and documentation mentioning
  23. #    features derived from or use of this software must display
  24. #    the following acknowledgement:
  25. #      "This product includes software developed by Digital Creations
  26. #      for use in the Z Object Publishing Environment
  27. #      (http://www.zope.org/)."
  28. #    In the event that the product being advertised includes an
  29. #    intact Zope distribution (with copyright and license included)
  30. #    then this clause is waived.
  31. # 5. Names associated with Zope or Digital Creations must not be used to
  32. #    endorse or promote products derived from this software without
  33. #    prior written permission from Digital Creations.
  34. # 6. Modified redistributions of any form whatsoever must retain
  35. #    the following acknowledgment:
  36. #      "This product includes software developed by Digital Creations
  37. #      for use in the Z Object Publishing Environment
  38. #      (http://www.zope.org/)."
  39. #    Intact (re-)distributions of any official Zope release do not
  40. #    require an external acknowledgement.
  41. # 7. Modifications are encouraged but must be packaged separately as
  42. #    patches to official Zope releases.  Distributions that do not
  43. #    clearly separate the patches from the original work must be clearly
  44. #    labeled as unofficial distributions.  Modifications which do not
  45. #    carry the name Zope may be packaged in any form, as long as they
  46. #    conform to all of the clauses above.
  47. # Disclaimer
  48. #   THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
  49. #   EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  50. #   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
  51. #   PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
  52. #   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  53. #   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  54. #   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
  55. #   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  56. #   ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  57. #   OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
  58. #   OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  59. #   SUCH DAMAGE.
  60. # This software consists of contributions made by Digital Creations and
  61. # many individuals on behalf of Digital Creations.  Specific
  62. # attributions are listed in the accompanying credits file.
  63. ##############################################################################
  64. __doc__='''Class for reading RDB files
  65.  
  66.  
  67. $Id: RDB.py,v 1.24.32.2 2000/07/17 15:03:55 brian Exp $'''
  68. __version__='$Revision: 1.24.32.2 $'[11:-2]
  69.  
  70. import regex, regsub
  71. from string import split, strip, lower, upper, atof, atoi, atol, find, join
  72. import DateTime
  73. from Missing import MV
  74. from array import array
  75. from Record import Record
  76. from Acquisition import Implicit
  77. import ExtensionClass
  78.  
  79. def parse_text(s):
  80.     if find(s,'\\') < 0 and (find(s,'\\t') < 0 and find(s,'\\n') < 0): return s
  81.     r=[]
  82.     for x in split(s,'\\\\'):
  83.         x=join(split(x,'\\n'),'\n')
  84.         r.append(join(split(x,'\\t'),'\t'))
  85.     return join(r,'\\')
  86.  
  87.  
  88. Parsers={'n': atof,
  89.          'i': atoi,
  90.          'l': atol,
  91.          'd': DateTime.DateTime,
  92.          't': parse_text,
  93.          }
  94.  
  95. class SQLAlias(ExtensionClass.Base):
  96.     def __init__(self, name): self._n=name
  97.     def __of__(self, parent): return getattr(parent, self._n)
  98.  
  99. class NoBrains: pass
  100.  
  101. class DatabaseResults:
  102.     """Class for reading RDB files
  103.     """
  104.     _index=None
  105.  
  106.     # We need to allow access to not-explicitly-protected
  107.     # individual record objects contained in the result.
  108.     __allow_access_to_unprotected_subobjects__=1
  109.  
  110.     def __init__(self,file,brains=NoBrains, parent=None, zbrains=None):
  111.  
  112.         self._file=file
  113.         readline=file.readline
  114.         line=readline()
  115.         self._parent=parent
  116.         if zbrains is None: zbrains=NoBrains
  117.  
  118.         comment_pattern=regex.compile('#')
  119.         while line and comment_pattern.match(line) >= 0: line=readline()
  120.  
  121.         line=line[:-1]
  122.         if line and line[-1:] in '\r\n': line=line[:-1]
  123.         self._names=names=split(line,'\t')
  124.         if not names: raise ValueError, 'No column names'
  125.  
  126.         aliases=[]
  127.         self._schema=schema={}
  128.         i=0
  129.         for name in names:
  130.             name=strip(name)
  131.             if not name:
  132.                 raise ValueError, 'Empty column name, %s' % name
  133.             if schema.has_key(name):
  134.                 raise ValueError, 'Duplicate column name, %s' % name
  135.             schema[name]=i
  136.             n=lower(name)
  137.             if n != name: aliases.append((n, SQLAlias(name)))
  138.             n=upper(name)
  139.             if n != name: aliases.append((n, SQLAlias(name)))
  140.             i=i+1
  141.  
  142.         self._nv=nv=len(names)
  143.         line=readline()
  144.         line=line[:-1]
  145.         if line[-1:] in '\r\n': line=line[:-1]
  146.         
  147.         self._defs=defs=split(line,'\t')
  148.         if not defs: raise ValueError, 'No column definitions'
  149.         if len(defs) != nv:
  150.             raise ValueError, (
  151.                 """The number of column names and the number of column
  152.                 definitions are different.""")
  153.         
  154.         i=0
  155.         self._parsers=parsers=[]
  156.         defre=regex.compile('\([0-9]*\)\([a-zA-Z]\)?')
  157.         self._data_dictionary=dd={}
  158.         self.__items__=items=[]
  159.         for _def in defs:
  160.             _def=strip(_def)
  161.             if not _def:
  162.                 raise ValueError, ('Empty column definition for %s' % names[i])
  163.             if defre.match(_def) < 0:
  164.                 raise ValueError, (
  165.                     'Invalid column definition for, %s, for %s'
  166.                     % _def, names[i])
  167.             type=lower(defre.group(2))
  168.             width=defre.group(1)
  169.             if width: width=atoi(width)
  170.             else: width=8
  171.  
  172.             try: parser=Parsers[type]
  173.             except: parser=str
  174.  
  175.             name=names[i]
  176.             d={'name': name, 'type': type, 'width': width, 'parser': parser}
  177.             items.append(d)
  178.             dd[name]=d
  179.             
  180.             parsers.append((i,parser))
  181.             i=i+1
  182.  
  183.         # Create a record class to hold the records.
  184.         names=tuple(names)
  185.  
  186.         class r(Record, Implicit, brains, zbrains):
  187.             'Result record class'               
  188.  
  189.         r.__record_schema__=schema
  190.         for k in filter(lambda k: k[:2]=='__', Record.__dict__.keys()):
  191.             setattr(r,k,getattr(Record,k))
  192.  
  193.         # Add SQL Aliases
  194.         d=r.__dict__
  195.         for k, v in aliases:
  196.             if not hasattr(r,k): d[k]=v
  197.  
  198.         if hasattr(brains, '__init__'):
  199.             binit=brains.__init__
  200.             if hasattr(binit,'im_func'): binit=binit.im_func
  201.             def __init__(self, data, parent, binit=binit):
  202.                 Record.__init__(self,data)
  203.                 binit(self.__of__(parent))
  204.  
  205.             r.__dict__['__init__']=__init__
  206.                     
  207.  
  208.         self._class=r
  209.  
  210.         # OK, we've read meta data, now get line indexes
  211.  
  212.         p=file.tell()
  213.         save=self._lines=array('i')
  214.         save=save.append
  215.         l=readline()
  216.         while l:
  217.             save(p)
  218.             p=p+len(l)
  219.             l=readline()
  220.  
  221.     def _searchable_result_columns(self): return self.__items__
  222.     def names(self): return self._names
  223.     def data_dictionary(self): return self._data_dictionary
  224.  
  225.     def __len__(self): return len(self._lines)
  226.  
  227.     def __getitem__(self,index):
  228.         if index==self._index: return self._row
  229.         file=self._file
  230.         file.seek(self._lines[index])
  231.         line=file.readline()
  232.         line=line[:-1]
  233.         if line and line[-1:] in '\r\n': line=line[:-1]
  234.         fields=split(line,'\t')
  235.         l=len(fields)
  236.         nv=self._nv
  237.         if l != nv:
  238.             if l < nv:
  239.                 fields=fields+['']*(nv-l)
  240.             else:
  241.                 raise ValueError, (
  242.                     """The number of items in record %s is invalid
  243.                     <pre>%s\n%s\n%s\n%s</pre>
  244.                     """ 
  245.                     % (index, ('='*40), line, ('='*40), fields))
  246.         for i, parser in self._parsers:
  247.             try: v=parser(fields[i])
  248.             except:
  249.                 if fields[i]:
  250.                     raise ValueError, (
  251.                         """Invalid value, %s, for %s in record %s"""
  252.                         % (fields[i], self._names[i], index))
  253.                 else: v=MV
  254.             fields[i]=v
  255.  
  256.         parent=self._parent
  257.         fields=self._class(fields, parent)
  258.         self._index=index
  259.         self._row=fields
  260.         if parent is None: return fields
  261.         return fields.__of__(parent)
  262.  
  263. File=DatabaseResults
  264.